import wx from 'weixin-js-sdk'
import lyRequest from '@/commons/framework/request.js'
export default {
	//判断是否在微信中
	isWechat: function() {
		var ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/micromessenger/i) == 'micromessenger') {
			// alert('是微信客户端')
			return true;
		} else {
			return false;
		}
	},
	initJssdk: function(callback) {
		let _this = this
		lyRequest.requestConfig.header = {
			'Accept': "application/json, text/javascript, */*; q=0.01",
			"Content-Type": "application/x-www-form-urlencoded;charset=utf-8;"
		};
		
		var url = encodeURIComponent(window.location.href.split('#')[0]); //获取当前url然后传递给后台获取授权和签名信息

		lyRequest.post("/ly/mp/busicen/cm/wxInvoice/getSignature.do", {
			url: url
		}).then(result => {
			if (result.data && result.data.result == '1') {
				wx.config({
					beta: true,
					debug: false,
					appId: result.data.rows.appid,
					timestamp: result.data.rows.timestamp,
					nonceStr: result.data.rows.nonceStr,
					signature: result.data.rows.signature,
					jsApiList: [
						'chooseInvoice'
					]
				});

				if (callback) {
					callback(result.data.rows);
				}
			}
		});
		lyRequest.requestConfig.header = {
			'Accept': "application/json, text/javascript, */*; q=0.01"
		};
	},
	chooseInvoice:function(callback){
		let _this = this
		if (!this.isWechat()) {
			return;
		}
		this.initJssdk(function(res) {
			wx.ready(function() {
				wx.checkJsApi({
					jsApiList: ['chooseInvoice'],
					success: function(res) {
						wx.invoke('chooseInvoice', {
							'timestamp': res.timestamp,
							'nonceStr': res.nonceStr
						}, function(res) {
							callback(res)
						});
					}
				});
			});
		});
	}
}
